<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="medicineName" label="药品名称" required>
        <uni-easyinput v-model="formData.medicineName"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="author" label="发货地">
        <uni-easyinput v-model="formData.author"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="brand" label="品牌" required>
        <uni-easyinput v-model="formData.brand"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="capacity" label="规格" required>
        <uni-easyinput v-model="formData.capacity"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="classify" label="分类" required>
        <uni-data-checkbox v-model="formData.classify" :localdata="formOptions.classify_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="coverImage" label="封面">
        <uni-file-picker file-mediatype="image" file-extname="jpg,png" return-type="object" v-model="formData.coverImage"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="price" label="单价" required>
        <uni-easyinput type="number" v-model="formData.price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="cheapPrice" label="折扣价">
        <uni-easyinput type="number" v-model="formData.cheapPrice"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="restCount" label="余量" required>
        <uni-easyinput type="number" v-model="formData.restCount"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="brief" label="商品详情">
        <uni-easyinput v-model="formData.brief" type="textarea" autoHeight maxlength="-1"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/medicine.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'medicine';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "medicineName": "",
        "author": "",
        "brand": "",
        "capacity": "",
        "classify": "",
        "coverImage": null,
        "price": 0,
        "cheapPrice": null,
        "restCount": 0,
        "brief": ""
      }
      return {
        formData,
        formOptions: {
          "classify_localdata": [
            {
              "text": "名医药膳",
              "value": "名医药膳"
            },
            {
              "text": "惠捷自选",
              "value": "惠捷自选"
            },
            {
              "text": "药品速购",
              "value": "药品速购"
            },
            {
              "text": "新药速递",
              "value": "新药速递"
            },
            {
              "text": "换药室",
              "value": "换药室"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("medicineName,author,brand,capacity,classify,coverImage,price,cheapPrice,restCount,brief").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
